﻿using DeHeng_Mes.Constant;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;

namespace DeHeng_Mes.Utils
{
    public static class MesLoginHelper
    {
        /// <summary>
        /// 获取德恒Token
        /// </summary>
        /// <param name="cancel"></param>
        /// <returns></returns>
        public static async Task<string> GetDhTokenAsync(CancellationToken cancel)
        {
            try
            {
                String dhToken = (string)CacheUtils.GetFromCache(SystemConstant.FACTORY_MES_TOKEN_CACHE_KEY);
                if (string.IsNullOrEmpty(dhToken))
                {
                    String user = SystemConstant.FACTORY_MES_USERNAME;
                    String password = SystemConstant.FACTORY_MES_PASSWORD;
                    double lose = SystemConstant.FACTORY_MES_TOKEN_CACHE_EXPIRY;
                    DateTimeOffset? timeOffset = lose <= 0 ? (DateTimeOffset?)null : DateTime.Now.AddMinutes(lose);
                    String url = "http://" + SystemConstant.FACTORY_MES_IP + ":" + SystemConstant.FACTORY_MES_PORT + "/dh-mes/api/login";

                    Dictionary<String, String> dic = new Dictionary<String, String>();
                    dic.Add("username", user);
                    dic.Add("password", password);

                    String response = await HttpUtils.HttpRequestAsync(url, null, HttpRequestType.POST, dic, cancel);
                    JObject jsonObject = JObject.Parse(response);
                    String token = jsonObject["token"]?.ToString();
                    CacheUtils.AddToCache(SystemConstant.FACTORY_MES_TOKEN_CACHE_KEY, token, timeOffset);
                    await AsyncLoggerDevice.WriteLogAsync("登录成功");
                    return token;
                }
                else
                {
                    await AsyncLoggerDevice.WriteLogAsync("当前已经登录");
                    return dhToken;
                }
            }
            catch (Exception ex)
            {
                await AsyncLoggerDevice.WriteLogAsync("登录失败：" + ex.Message);
                throw new Exception("登录失败");
            }

        }


        /// <summary>
        /// 续签Token
        /// </summary>
        /// <returns></returns>
        public static void RefreshToken()
        {
            double lose = SystemConstant.FACTORY_MES_TOKEN_CACHE_EXPIRY;
            CacheUtils.UpdateCacheExpiration(SystemConstant.FACTORY_MES_TOKEN_CACHE_KEY, DateTime.Now.AddMinutes(lose));
        }
    }
}
